﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace NougakudoLauncher
{
    class Program
    {

        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("no argument");
                Logging.Write("NougakudoLauncher: NougakudoLauncher: No argument.", Logging.LogType.ERROR);
                return 1;
            }

#if DEBUG
            Logging.Write("NougakudoLauncher: CommandLine args ={0}.", new object[] { args[0] }, Logging.LogType.INFO);
            Console.WriteLine("CommandLine args = {0}", args[0]);
#endif
            string[] commands = GetArgs(args[0]);
#if DEBUG
            Logging.Write("NougakudoLauncher: ruby args1 ={0}.", new object[] { commands[0] }, Logging.LogType.INFO);
            Logging.Write("NougakudoLauncher: ruby args2 ={0}.", new object[] { commands[1] }, Logging.LogType.INFO);
#endif
            var ruby = new Startup();
            bool result = false;
            string command3 = "";                                   // BUNDLE_GEMFILE environment variable
            if (commands.Length >= 3)
            {
                command3 = commands[2];
            }
            result = ruby.Run(commands[0], commands[1], command3);  // Add BUNDLE_GEMFILE environment parameter.
            if (!result)    // Add ruby start error.
            {
                Logging.Write("NougakudoLauncher: ruby start error. ", Logging.LogType.ERROR);
                Console.WriteLine("NougakudoLauncher: ruby start error. ");
                return 1;
            }

#if DEBUG
            Logging.Write("NougakudoLauncher: press any key for stop. ", Logging.LogType.INFO);
#endif
            Console.WriteLine("Press any key. 終了を呼び出します");
            Console.ReadKey();
            return 0;
        }

        static string[] GetArgs(string file)
        {
            var commnds = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, file);
            try
            {
                return File.ReadAllLines(commnds);
            }
            catch
            {
                return null;
            }
        }
    }
}
